﻿using FairyGUI;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

public class PackHeroPage : BasePage
{
    private GList lsItems;

    public PackHeroPage(GComponent vie) : base(vie)
    {
        lsItems = this.view.GetChild("n7").asList;

        lsItems.onClickItem.Add(OnPackItemClick);
    }

    public override void Show()
    {
        MsgListenerMgr.AddMsgListener(MsgListenerType.PackHeroChange, OnPackHeroChange);
        this.Load();
    }

    public override void Close()
    {
        MsgListenerMgr.RemoveMsgListener(MsgListenerType.PackHeroChange, OnPackHeroChange);
    }

    private void Load()
    {
        lsItems.RemoveChildrenToPool();
        List<Hero> heros = GameNetwork.Player.PackHeroMgr.GetAll();
        heros.Sort(HeroComparer);
        foreach (Hero hero in heros)
        {
            InitHero initHero = hero.InitHero;
            if (initHero == null)
            {
                continue;
            }

            GComponent button = lsItems.GetFromPool("ui://f2iijc3nm9n1bm").asCom;
            button.data = hero.id;

            GTextField tfName = button.GetChild("n1").asTextField;
            tfName.text = initHero.name;
            tfName.color = CommonUtil.GetHeroPinZhiColor(initHero.quality);

            GTextField tfDuJie = button.GetChild("n2").asTextField;
            tfDuJie.text = CommonUtil.GetDuJieName(hero.DuJieLevel);

            for (int j = 1; j <= 5; j++)
            {
                GImage cpt = button.GetChild("bg" + j.ToString()).asImage;
                if (cpt != null)
                {
                    cpt.visible = j == initHero.quality;
                }
            }

            lsItems.AddChild(button);
        }
    }

    private int HeroComparer(Hero a, Hero b)
    {
        int sa = 0;
        if (a.InitHero != null)
        {
            sa = a.InitHero.quality;
        }

        int sb = 0;
        if (b.InitHero != null) 
        {
            sb = b.InitHero.quality;
        }

        if (sa > sb)
        {
            return -1;
        }
        else if (sa < sb)
        {
            return 1;
        }
        else
        {
            return 0;
        }
    }

    private void OnPackItemClick(EventContext context)
    {
        GButton button = lsItems.GetChildAt(lsItems.selectedIndex).asButton;
        if (button == null)
        {
            return;
        }
        long id = (long)button.data;
        if (GameNetwork.Player.PackHeroMgr.TryGet(id, out Hero hero))
        {
            PopupPanelManager.Open<HeroInfoPanel>(hero);
        }
    }

    private void OnPackHeroChange(object[] para)
    {
        Load();
    }
}
